import os
import sys

# 添加项目根目录到 Python 路径
current_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(current_dir)

import cv2
from src.config import CAMERA_ID, FRAME_WIDTH, FRAME_HEIGHT

def generate_frames():
    """
    生成视频帧的生成器函数
    """
    # 初始化摄像头
    camera = cv2.VideoCapture(CAMERA_ID)
    camera.set(cv2.CAP_PROP_FRAME_WIDTH, FRAME_WIDTH)
    camera.set(cv2.CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT)
    
    while True:
        # 读取摄像头帧
        success, frame = camera.read()
        if not success:
            break
        else:
            # 将帧编码为JPEG格式
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            
            # 使用生成器返回帧
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') 